import tornado.websocket
import tornado.ioloop
import datetime
from threading import Thread
import asyncio
import json
import asyncio
import websockets

# 设置全局变量
users = set()
remessage = ''

# ----------------------------服服务端---------------------------
class answer:
    def send(self,ques):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        print(ques)
        dics = json.dumps(ques,ensure_ascii=False)
        print(dics)
        for u in users:
            u.write_message(dics)


class web_add:

    def sear(self,mess):
        t1 = Thread(target=an.send(mess))
        t1.start()

    def stop(self):
        pass

    # 处理命令
    def mse(self):
        message = json.loads(remessage)
        self.sear(message)


class WebSocketHandler(tornado.websocket.WebSocketHandler):

    def open(self):
        users.add(self)
        self.write_message(u"[%s]-[%s]-进入" % (self.request.remote_ip, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
        print(u"[%s]-[%s]-进入" % (self.request.remote_ip, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))

    def on_message(self, message):
        global remessage
        remessage = message
        add.mse()


    def on_close(self):
        # 用户关闭连接后从容器中移除用户
        users.remove(self)
        print(u"[%s]-[%s]-离开" % (self.request.remote_ip, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))

    def check_origin(self, origin):
        return True


application = tornado.web.Application([
    (r"/", WebSocketHandler),
])

add = web_add()
an = answer()


# ------------------------客户端------------------------

async def client(js):
    async with websockets.connect("ws://127.0.0.1:9016") as websocket:
        await websocket.send(js)
        await websocket.recv()


# 数据下发
def send(json_param):
    asyncio.run(client(json_param))
